package com.sky.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.content.dto.CourseCategoryTreeDto;
import com.sky.content.mapper.CourseCategoryMapper;
import com.sky.content.model.po.CourseCategory;
import com.sky.content.service.CourseCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 尹稳健~
 * @version 1.0
 * @time 2023/6/7
 */
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Resource
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        List<CourseCategory> courseCategories = courseCategoryMapper
                .selectList(new LambdaQueryWrapper<CourseCategory>().eq(CourseCategory::getParentid, id)
                        .orderByAsc(CourseCategory::getOrderby));
        System.err.println(courseCategories);
        return courseCategories.stream().map(this::buildCourseCategoryTree).collect(Collectors.toList());
    }

    private CourseCategoryTreeDto buildCourseCategoryTree(CourseCategory category) {
        CourseCategoryTreeDto dto = new CourseCategoryTreeDto();
        BeanUtils.copyProperties(category, dto);
        List<CourseCategory> children = courseCategoryMapper.selectList(new LambdaQueryWrapper<CourseCategory>()
                .eq(CourseCategory::getParentid, category.getId())
                .orderByAsc(CourseCategory::getOrderby));
        if (!children.isEmpty()) {
            dto.setChildrenTreeNodes(children.stream().map(this::buildCourseCategoryTree)
                    .collect(Collectors.toList()));
        }
        return dto;
    }
}
